<?php
namespace Admin\Controller;
use Think\Controller;
class RoleController extends Controller {
    public function lists(){
        $roles=M('role')->select();
        $this->assign('roles',$roles);
        $this->display();
    }

    public function add(){
        if(IS_POST){
            $Role=D('Role');
            if(!$Role->create()){
                $this->error($Menu->getError());
            }else{
                if($Role->add()){
                    $this->success('添加成功');
                }else{
                    $this->error('添加失败');
                }
            }
        }else{
            $this->display('add');
        }
    }

    public function edit(){
        if(IS_POST){
            $roleids=I('post.roleids');
            $role_id=I('post.role_id',0);

            M('role_menu')->where(['role_id'=>$role_id])->delete();
            foreach($roleids as $key => $value){
                M('role_menu')->data(['role_id'=>$role_id,'menu_id'=>$value])->add();
            }

            $this->success('修改成功');
        }else{
            $id=I('get.id',0);
            $role=M('role')->where(['id'=>$id])->find();

            $role_menu_json=M('role_menu')->where(['role_id'=>$id])->select();
            $menu_tree=getMenuTree();
            $this->assign('menu_tree',$menu_tree);
            $this->assign('role_menu_json',json_encode($role_menu_json,true));


            $this->assign('role',$role);
            $this->display('edit');
        }
    }


    public function del(){
        $id=I('post.id',0);
        if(M('role')->where(['id'=>$id])->delete()){
            M('role_menu')->where(['role_id'=>$id])->delete();
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }


    public function forbidden(){
        $id=I('post.id',0);
        $status=I('post.status',0);
        $update_res=M('role')->where(['id'=>$id])->save(['status'=>!$status]);

        if($update_res){
            $this->success('修改成功');
        }else{
            $this->error('修改失败');
        }

    }
}